{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fib(n):\n",
    "    if n < 2:\n",
    "        return n\n",
    "\n",
    "    return fib(n - 1) + fib(n - 2)\n",
    "\n",
    "\n",
    "fib(0), fib(1), fib(2), fib(3), fib(4), fib(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fib(36)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Cache:\n",
    "    def __init__(self, limit=int(1e5)):\n",
    "        from sys import setrecursionlimit\n",
    "        from functools import lru_cache\n",
    "\n",
    "        setrecursionlimit(limit)            # reset recursion limit\n",
    "\n",
    "        self.lru_cache = lru_cache\n",
    "\n",
    "    def func(self):\n",
    "        return self.lru_cache()             # return key is function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cache = Cache()\n",
    "\n",
    "@cache.func()                               # use cache to accelerate recursion\n",
    "def fib_cached(n):\n",
    "    if n < 2:\n",
    "        return n\n",
    "\n",
    "    return fib_cached(n - 1) + fib_cached(n - 2)\n",
    "\n",
    "fib(0), fib(1), fib(2), fib(3), fib(4), fib(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fib_cached(36)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "3a176caed2e623e3a36a87b094ae4f1cc68623d3a88a2d36a2ea84f7c5d7277a"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
